<style scoped>

@import 'vuepc.css';

</style>
<template>
  <div style="width:100%; height:100%;">
    <el-card class="box-card">
      <el-form
        :inline="true"
        :rules="rules"
        ref="ruleForm"
        :model="queryForm"
        class="demo-form-inline">
        <el-form-item prop="systemUuid" label="系统">
          <el-select clearable
                     filterable
                     v-model="queryForm.systemUuid"
                     @change="refreshUseCaseOptions"
                     placeholder="请选择系统">
            <el-option
              v-for="item in systemOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="useCaseUuid" label="用例">
          <el-select :disabled="queryForm.systemUuid === ''"
                     clearable filterable v-model="queryForm.useCaseUuid" placeholder="请选择用例">
            <el-option
              v-for="item in useCaseOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="TraceId">
          <el-input v-model="queryForm.traceId" placeholder="精准查询"></el-input>
        </el-form-item>
        <el-form-item label="bizNo">
          <el-input v-model="queryForm.orderSerialNo" placeholder="精准查询"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="query">查询</el-button>
        </el-form-item>
      </el-form>

      <div style="width:100%; height:100%;" id="container"></div>
    </el-card>

    <el-dialog
      :title="dialogTableTitle"
      append-to-body
      width="75%"
      :visible.sync="dialogTableVisible">
      <el-table
        :header-cell-style="{background:'#eef1f6',color:'#606266'}"
        :data="currentBuryings"
        border
        :default-sort="{prop: 'updateTime', order: 'descending'}"
        style="width: 100%; margin-top: 20px;font-size: 10px">
        <el-table-column
          align="center"
          prop="systemKey"
          label="systemKey">
        </el-table-column>
        <el-table-column
          align="center"
          prop="useCase"
          label="useCase">
        </el-table-column>
        <el-table-column
          align="center"
          :show-overflow-tooltip="true"
          prop="traceId"
          label="traceId">
        </el-table-column>
        <el-table-column
          align="center"
          prop="businessNo"
          label="businessNo">
        </el-table-column>
        <el-table-column
          align="center"
          prop="module"
          label="module">
        </el-table-column>
        <el-table-column
          align="center"
          prop="category"
          label="category">
        </el-table-column>
        <el-table-column
          align="center"
          prop="subCategory"
          label="subCategory">
        </el-table-column>
        <el-table-column
          align="center"
          prop=""
          label="日志级别">
          <template slot-scope="scope">
            <span :style="loggerLevelStyle(scope.row.loggerLevel)"><b>{{ scope.row.loggerLevel }}</b></span>
          </template>
        </el-table-column>
        <el-table-column
          sortable
          align="center"
          width="150"
          label="修改时间">
          <template slot-scope="scope">
            {{ baseDateFormat(scope.row.updateTime) }}
          </template>
        </el-table-column>
        <el-table-column
          fixed="right"
          align="center"
          width="50"
          label="操作">
          <template slot-scope="scope">
            <el-button style="margin-left: 0px;color: #a70fe3" type="text" size="mini" @click="showVue(scope.row)">
              查看
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <el-dialog
      :visible.sync="dialogVisible"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
      :fullscreen="fullScreen"
      append-to-body
      width="80%"
      :before-close="clearForm">
      <!-- 自定义title -->
      <div slot="title" class="header-title">
        <span class="title-text">{{ dialogTableTitle + '[组件展示]' }}</span>
        <el-button style="float: right; margin-right: 20px;margin-top: -10px" size="=mini" type="text" icon="el-icon-full-screen" @click="fullScreen = !fullScreen"></el-button>
      </div>

      <div id="app">
        <vuep class="hide-code" :template="vueCode" :scope="this"></vuep>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="clearForm">关 闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {systemSelector, useCaseSelector} from "@/api/loadSelectorApi";
import {graphQuery} from "@/api/graph";
import {Graph} from "@antv/x6";
import {Snapline} from "@antv/x6-plugin-snapline";
import {Selection} from "@antv/x6-plugin-selection";
import {Scroller} from "@antv/x6-plugin-scroller";
import {DagreLayout} from "@antv/layout";
import da from "element-ui/src/locale/lang/da";

export default {
  name: "bic-singleton-view",
  data() {
    return {
      dialogVisible: false,
      fullScreen: false,
      queryForm: {
        systemUuid: '',
        useCaseUuid: '',
        traceId: '',
        orderSerialNo: ''
      },
      systemOptions: [],
      useCaseOptions: [],
      rules: {
        systemUuid: [
          {required: true, message: '此项必填', trigger: 'change'}
        ],
        useCaseUuid: [
          {required: true, message: '此项必填', trigger: 'change'},
        ],
      },
      currentGraphData: {},
      graphHolder: undefined,
      dialogTableVisible: false,
      dialogTableTitle: '节点数据',
      currentBuryings: [],
      vueCode: '',
      nodeVueType: '',
      pluginContext: {},
    }
  },
  async created() {
    let vm = this
    vm.systemOptions = await systemSelector()
  },
  methods: {
    async query() {
      let vm = this
      vm.$refs['ruleForm'].validate(async (valid) => {
        if (valid) {
          let loading = vm.loading();
          let ret = await graphQuery(vm.queryForm)
          if (ret.ok) {
            if (ret.data.graph === null) {
              vm.$message({type: 'error', message: '查询失败：此用例没有定义纠察图'});
            } else {
              vm.currentGraph = ret.data.graph
              vm.doRefresh()
            }
          } else {
            vm.$message({type: 'error', message: '查询失败：' + ret.message});
          }
          loading.close()
        }
      })
    },
    clearForm() {
      let vm = this
      vm.dialogVisible = false
      vm.vueCode = ''
      vm.pluginContext = {}
      vm.fullScreen = false
    },
    async refreshUseCaseOptions() {
      let vm = this
      vm.queryForm.useCaseUuid = ''
      if (vm.queryForm.systemUuid === '') {
        vm.useCaseOptions = []
      } else {
        vm.useCaseOptions = await useCaseSelector(vm.queryForm.systemUuid)
      }
    },
    loggerLevelStyle(loggerLevel) {
      if (loggerLevel === 'DEBUG') {
        return "color: #5ecaf1"
      }
      if (loggerLevel === 'ERROR') {
        return "color: red"
      }
      if (loggerLevel === 'INFO') {
        return "color: #a2f375"
      }
      if (loggerLevel === 'WARNING') {
        return "color: #efc067"
      }
      return ""
    },
    showVue(row) {
      let vm = this
      vm.pluginContext = row
      if (vm.nodeVueType === 'DIALOG') {
        vm.dialogVisible = true
      } else if (vm.nodeVueType === 'OPEN_TAG') {
        // 跳转到新标签页
        localStorage.setItem('pluginContext', JSON.stringify(row))
        localStorage.setItem('vueCode', vm.vueCode)
        vm.$router.push({path: '/bicView/landingGraph'})
      } else {
        vm.dialogVisible = true
      }
      vm.$forceUpdate()
    },
    doRefresh() {
      let vm = this
      let graph = undefined
      if (vm.graphHolder !== undefined) {
        vm.graphHolder.dispose()
      }
      graph = vm.newOneGraph();
      vm.graphHolder = graph

      const data = {
        nodes: vm.currentGraph.nodes,
        edges: vm.currentGraph.edges
      }

      console.log(data)
      graph.fromJSON(data)

      // https://x6.antv.antgroup.com/tutorial/basic/events
      // graph.addNode({})
      // graph.addNodes(demoViewNodeData)
      // graph.centerContent()

      graph.on('node:click', ({e, x, y, node, view}) => {
        if (node.store.data.buryings !== undefined && node.store.data.buryings !== null) {
          vm.currentBuryings = node.store.data.buryings
        } else {
          vm.currentBuryings = []
        }
        vm.dialogTableTitle = node.store.data.attrs.label.text + ' [节点数据]'
        vm.vueCode = node.store.data.nodeVueCode
        vm.nodeVueType = node.store.data.nodeVueType
        vm.dialogTableVisible = true
        vm.$forceUpdate()
      })
      //
      // graph.on('node:mouseenter', ({e, node, view}) => {
      //   alert("eeee")
      // })
      // graph.on('cell:click', ({ e, x, y, cell, view }) => {})
      //   graph.on('node:click', ({ e, x, y, node, view }) => {})
      //   graph.on('edge:click', ({ e, x, y, edge, view }) => {})
      //   graph.on('blank:click', ({ e, x, y }) => {})
      //
      //   graph.on('cell:mouseenter', ({ e, cell, view }) => {})
      //   graph.on('node:mouseenter', ({ e, node, view }) => {})
      //   graph.on('edge:mouseenter', ({ e, edge, view }) => {})
      //   graph.on('graph:mouseenter', ({ e }) => {})

      graph.on('edge:mouseenter', ({e, edge, view}) => {
        if (edge.store.data.historyInfo == null) {
          edge.store.data.historyInfo = {}
        }
        edge.store.data.historyInfo.attrs = edge.getAttrs()
        edge.store.data.historyInfo.labels = edge.getLabels()
        let tempData = edge.store.data;
        edge.setAttrs(tempData.consumerInfo.attrs)
        edge.setLabels(tempData.consumerInfo.labels)
      })

      graph.on('edge:mouseleave', ({e, edge, view}) => {
        edge.setAttrs(edge.store.data.historyInfo.attrs)
        edge.setLabels(edge.store.data.historyInfo.labels)
      })

      graph.use(
        new Snapline({
          enabled: true,
          clean: false,
        }),
      )

      graph.use(
        new Selection({
          enabled: true,
          multiple: true,
          rubberband: true,
          movable: true,
          showNodeSelectionBox: true,
        }),
      )

      graph.use(
        new Scroller({
          enabled: true,
          pannable: true,
          padding: 20
        }),
      )

      // https://x6.antv.antgroup.com/temp/layout#dagre
      const dagreLayout = new DagreLayout({
        type: 'dagre',
        rankdir: 'LR',
        align: undefined,
        ranksep: 50,
        nodesep: 15,
        controlPoints: true,
        preventOverlap: true
      })

      const newModel = dagreLayout.layout(data)

      graph.fromJSON(newModel)
    },
    newOneGraph() {
      return new Graph({
        container: document.getElementById('container'),
        width: document.body.scrollWidth - 20,
        height: document.body.scrollHeight - 90,
        autoResize: false,
        interacting: {
          edgeLabelMovable: true,
        },
        grid: {
          size: 10,
          visible: true,
          type: 'doubleMesh',
          args: [
            {
              color: '#eee',
              thickness: 1,
            },
            {
              color: '#ddd',
              thickness: 1,
              factor: 4,
            },
          ],
        },
        background: {
          color: '#ffffff',
        },
        connecting: {
          allowBlank: true,
        },
        selecting: {
          enabled: true,
          className: 'node-selecting',
          rubberband: true,
          rubberNode: true,
          movable: true
        },
        snapline: {
          enabled: true,
          sharp: true,
        },
        keyboard: {
          enabled: true
        },
      })
    }
  }
}
</script>

